import React, { useEffect, useState } from 'react';
import './index.less';
import axios from 'axios';
type Props = {};

export default function index({}: Props) {
  let [inp, setinp] = useState('');
  let [shuju, setshuju] = useState([]);
  let [sess, setsess] = useState([]);
  let [show, setshow] = useState(false);
  useEffect(() => {
    if (sessionStorage.getItem('shuju') === null) {
      setsess([]);
    } else {
      let asd = JSON.parse(sessionStorage.getItem('shuju'));
      console.log(asd);
      setsess((sess = asd));
      console.log(sess);
    }
  }, []);
  return (
    <div className="xl3">
      <div className="div">
        <div
          className="lishi"
          style={{ display: show === false ? 'none' : '' }}
        >
          <p>历史记录</p>
          {sess.map((item, index) => {
            return <div key={index}>{item}</div>;
          })}
        </div>
        <input
          type="text"
          value={inp}
          onChange={(e) => {
            setinp((inp = e.target.value));
          }}
          onClick={() => {
            setshow(true);
          }}
        />{' '}
        <button
          onClick={() => {
            setshow(false);
            let aaa = [];
            if (sessionStorage.getItem('shuju') === null) {
              aaa.unshift(inp);
              sessionStorage.setItem('shuju', JSON.stringify(aaa));
            } else {
              let asd = sessionStorage.getItem('shuju');
              aaa = JSON.parse(asd);
              // console.log(aaa.length);
              if (aaa.length >= 6) {
                let bbb = aaa.pop();
                // console.log(1,bbb);
                aaa.unshift(inp);
                // console.log(2,aaa);
                sessionStorage.setItem('shuju', JSON.stringify(aaa));
              } else {
                aaa.unshift(inp);
                sessionStorage.setItem('shuju', JSON.stringify(aaa));
              }
            }
            axios
              .get(`http://localhost:3001/posts?title_like=${inp}`)
              .then((res) => {
                // console.log(res.data);
                setshuju(res.data);
              });
          }}
        >
          搜索
        </button>
        <div className="iin">
          {shuju.map((item, index) => {
            return (
              <div className="content" key={index}>
                <div>
                  <img src={item.tup} alt="" />
                </div>
                <div>{item.title}</div>
                <div>￥{item.price}</div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}
